<template>
  <g-dialog
    width="50%"
    :title="getTitle"
    :visible.sync="dialogVisible"
    :isShowBtn="true"
    append-to-body
    :destroy-on-close="true"
    :beforeClose="hangleOnclose"
  >
    <div v-loading.fullscreen.lock="fullLoading">
      <el-form ref="form" :rules="rules" :model="form" label-width="100px">
        <el-row :gutter="12">
          <el-col>
            <el-form-item label="上级菜单" prop="parent">
              <el-cascader
                v-model="form.parent"
                class="w-full"
                filterable
                clearable
                :options="menuOpts"
                :props="{ label: 'title', value: 'id', checkStrictly: true, emitPath: false }"
                :show-all-levels="false"
                placeholder="请选择上级菜单"
                @change="changeParent"
              >
              </el-cascader>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="类型" prop="menu_type">
              <el-radio-group v-model="form.menu_type" @input="changeType">
                <el-radio-button :label="0">目录</el-radio-button>
                <el-radio-button :label="1">菜单</el-radio-button>
                <el-radio-button :label="2">按钮</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="权限标识" prop="permission">
              <el-input v-model="form.permission" placeholder="请输入权限标识" maxlength="32" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12" v-if="form.menu_type === 0">
          <el-divider content-position="left">目录信息</el-divider>

          <el-col :span="12">
            <el-form-item :label="getName" prop="name">
              <el-input v-model="form.name" :placeholder="'请输入' + getName" maxlength="30" show-word-limit />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item prop="icon">
              <template slot="label">
                <span>图标</span>
                <el-popover placement="top" title="图标名称" width="300" trigger="hover">
                  <div class="form-tip">以连字符形式命名，比如：<el-tag>el-icon-setting</el-tag></div>
                  <i slot="reference" class="el-icon-question"></i>
                </el-popover>
              </template>

              <el-input v-model="form.icon" placeholder="请输入图标" maxlength="30" show-word-limit />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="路由地址" prop="path">
              <el-input v-model="form.path" placeholder="请输入路由地址" maxlength="50" show-word-limit />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="排序" prop="order_num">
              <el-input-number v-model="form.order_num"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12" v-if="form.menu_type === 1">
          <el-divider content-position="left">菜单信息</el-divider>
          <el-col :span="12">
            <el-form-item :label="getName" prop="title">
              <el-input v-model="form.title" :placeholder="'请输入' + getName" maxlength="30" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="icon">
              <template slot="label">
                <span>图标</span>
                <el-popover placement="top" title="图标名称" width="300" trigger="hover">
                  <div class="form-tip">以连字符形式命名，比如：<el-tag>el-icon-setting</el-tag></div>
                  <i slot="reference" class="el-icon-question"></i>
                </el-popover>
              </template>

              <el-input v-model="form.icon" placeholder="请输入图标" maxlength="30" show-word-limit />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="路由地址" prop="path">
              <el-input v-model="form.path" placeholder="请输入路由地址" maxlength="50" show-word-limit />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="排序" prop="order_num">
              <el-input-number v-model="form.order_num"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组件名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入组件名称" maxlength="30" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组件路径" prop="component">
              <el-input v-model="form.component" placeholder="请输入组件路径" maxlength="50" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12" v-if="form.menu_type === 2">
          <el-col :span="12">
            <el-form-item :label="getName" prop="name">
              <el-input v-model="form.name" :placeholder="'请输入' + getName" maxlength="30" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="order_num">
              <el-input-number v-model="form.order_num"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="是否启用" prop="status">
              <el-switch v-model="form.status" :active-value="1" :inactive-value="0"> </el-switch>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="是否缓存" prop="cache">
              <el-switch v-model="form.cache" :active-value="1" :inactive-value="0"> </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="g-dialog-bottom-action">
      <el-button @click="handleClose" size="small">取消</el-button>
      <el-button type="primary" @click="handleSubmit()" size="small">提交</el-button>


    </div>
  </g-dialog>
</template>

<script>
import { addMenuApi, updateMenuApi, detailMenuApi, getMenuTreeApi } from '@/api/menu-api';
export default {
  name: 'CreateMenu',
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    editId: {
      type: [Number, String],
      default: 0
    },

    isChild: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      clickCount: 0,

      localVisible: this.visible,
      fullLoading: false,
      handleThrottledSubmit: null,
      detailData: {},
      form: {
        parent: null, // 上级菜单
        title: '', // 菜单名称
        menu_type: 1, // 类型
        permission: '', // 权限标识
        icon: '', // 图标名称
        name: '', // 组件名称
        path: '', // 路由地址
        component: '', // 组件路径
        order_num: 1, // 菜单排序
        status: 1, // 状态
        cache: 0 // 是否缓存
      },
      rules: {
        title: [
          {
            required: true,
            message: '不能为空'
          }
        ],
        permission: [
          {
            required: true,
            message: '不能为空'
          }
        ],
        order_num: [
          {
            required: true,
            message: '不能为空'
          }
        ],
        path: [
          {
            required: true,
            message: '不能为空'
          }
        ],
        cache: [
          {
            required: true,
            message: '不能为空'
          }
        ],
        status: [
          {
            required: true,
            message: '不能为空'
          }
        ]
      }
    };
  },
  computed: {
    isUpdate() {
      return Boolean(this.editId);
    },
    getTitle() {
      return this.isUpdate ? (this.isChild ? '添加菜单' : '编辑菜单') : '新增菜单';
    },
    getName() {
      let type = this.form.menu_type;

      const typeMap = new Map([
        [0, '目录名称'],
        [1, '菜单名称'],
        [2, '按钮名称']
      ]);

      return typeMap.get(type);
    },
    dialogVisible: {
      get() {
        return this.localVisible;
      },
      set(val) {
        this.$emit('update:visible', val);
      }
    }
  },
  created() {},

  mounted() {
    this.getMenuTree();

    // 添加默认为按钮
    if (this.isChild) {
      this.form.type = 2;
    }
    if (this.isUpdate) {
      this.getDetail();
    }
  },

  methods: {
    async getMenuTree() {
      try {
        const { data } = await getMenuTreeApi();
        this.menuOpts = data;
      } catch (err) {
        console.warn(err);
      }
    },
    async getDetail() {
      try {
        const { data } = await detailMenuApi(this.editId);

        // 不是添加，即为编辑
        if (!this.isChild) {
          for (let key in this.form) {
            if (key === 'parent') continue;
            this.form[key] = data[key];
          }
          // 上级菜单
          this.form.parent = data?.parent?.id ?? null;
        } else {
          // 当前菜单
          this.form.parent = data?.id ?? null;
        }
      } catch (err) {
        console.warn(err);
      } finally {
        this.fullLoading = false;
      }
    },

    beforeSubmit() {
      const params = {
        ...this.form
      };
      return params;
    },
    handleSubmit() {
      this.$refs['form'].validate(async (valid) => {
        if (!valid) return false;

        try {
          this.fullLoading = true;

          let params = this.beforeSubmit();

          let _code = 0;
          if (this.isUpdate && !this.isChild) {
            params.id = this.editId;
            const { code } = await updateMenuApi(params);
            _code = code;
          } else {
            const { code } = await addMenuApi(params);
            _code = code;
          }

          if (_code === 200) {
            this.$modal.msgSuccess('');
            this.handleClose();
          }
        } catch (err) {
          console.warn(err);
        } finally {
          this.fullLoading = false;
        }
      });
    },
    // 点击icon-close触发
    hangleOnclose() {
      this.handleClose();
    },

    handleClose() {
      this.dialogVisible = false;
      this.$emit('close-create');
    },

    changeType(val) {
      this.form.order = 1;
    },
    changeParent(val) {
      console.log(val);
    },


   handleClick() {
      this.clickCount++;
      console.log('按钮被点击了', this.clickCount, '次');
    }
  }
};
</script>

<style lang="scss" scoped></style>
